import { HttpException, Injectable } from '@nestjs/common';
import { CreateTreeDto } from './dto/create-tree.dto';
import { UpdateTreeDto } from './dto/update-tree.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Tree } from './entities/tree.entity';
import { IsNull, Not, Repository } from 'typeorm';
import dayjs from 'dayjs';
import crc32 from 'crc32';
import { Random, MersenneTwister19937 } from 'random-js';

@Injectable()
export class TreeService {
  constructor(
    @InjectRepository(Tree)
    private readonly treeRepo: Repository<Tree>,
  ) {}

  async create(createTreeDto: CreateTreeDto) {
    let one2 = await this.treeRepo.findOneBy({
      sign: createTreeDto.sign ? createTreeDto.sign : IsNull(),
    });

    if (createTreeDto.sign && one2) {
      throw new HttpException('树木id重复了', 400);
    }

    one2 = {} as Tree;

    const engine = MersenneTwister19937.autoSeed();
    const random = new Random(engine);

    const input =
      createTreeDto.cardNo + dayjs().valueOf() + random.integer(1, 110000);
    one2.sign = crc32(input);
    one2.cardNo = createTreeDto.cardNo + dayjs().valueOf();
    await this.treeRepo.save(one2);
    return {
      url: 'http://120.48.82.87/treeShow?sign=' + one2.sign,
      sign: one2.sign,
    };
  }

  findAll() {
    return `This action returns all tree`;
  }

  async findOne(id: string) {
    const one = await this.treeRepo.findOneBy({
      sign: id,
    });
    // if (!one) {
    //   throw new HttpException('您未填写该信息', 400);
    // }
    return one;
  }

  async update(updateTreeDto: UpdateTreeDto) {
    let ont = await this.treeRepo.findOne({
      where: {
        sign: Not(updateTreeDto.sign),
        cardNo: updateTreeDto.cardNo,
      },
    });
    console.log('---------1', ont);
    if (!(ont == undefined || ont == null)) {
      if (
        ont.cardNo == updateTreeDto.cardNo &&
        ont.sign != updateTreeDto.sign
      ) {
        throw new HttpException('树木编号重复了', 400);
      }
    } else {
      ont = await this.treeRepo.findOne({
        where: {
          sign: updateTreeDto.sign,
        },
      });
    }

    // const engine = MersenneTwister19937.autoSeed();
    // const random = new Random(engine);

    // const input =
    //   createTreeDto.cardNo + dayjs().valueOf() + random.integer(1, 110000);
    // if (!createTreeDto.sign) {
    //   createTreeDto.sign = crc32(input);
    // }
    ont = Object.assign(ont, updateTreeDto);
    await this.treeRepo.save(ont);
    return ont;
  }

  remove(id: number) {
    return `This action removes a #${id} tree`;
  }
}
